package org.example.project.search.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.example.project.search.data.Suggestion
import kotlin.math.round

/**
 * 记录卡片项 - 普通词条
 */
@Composable
fun BasicRecordItem(item: Suggestion) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column {
            BasicRecordTitle(item)
        }
    }
}

/**
 * 记录卡片项 - 搜索直达
 */
@Composable
fun SearchDirectRecordItem(item: Suggestion) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        BasicRecordTitle(item)
    }
}

/**
 * 记录卡片项 - 猜你喜欢
 */
@Composable
fun GuessRecordItem(item: Suggestion) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp, bottom = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            item.name ?: "", fontSize = 14.sp, fontWeight = FontWeight.W500,
            modifier = Modifier.padding(end = 10.dp)
        )
        LazyRow(
            Modifier.fillMaxWidth(1f),
            horizontalArrangement = Arrangement.spacedBy(4.dp)
        ) {
//            items(item.guessList) {
//                Box(
//                    Modifier
//                        .background(Color(0x08000000), shape = RoundedCornerShape(16.dp))
//                        .clip(RoundedCornerShape(16.dp))
//                        .clickable { }
//                        .padding(top = 5.dp, bottom = 5.dp, start = 10.dp, end = 10.dp)
//                ) {
//                    SecondText(it, color = Color.Black)
//                }
//            }
        }
    }
}

/**
 * 记录卡片项 - 地铁站
 */
@Composable
fun MetroRecordItem(item: Suggestion) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 8.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.Top
        ) {
            Column {
                BasicRecordTitle(item)
                if (!item.sgPassLines.isNullOrEmpty()) {
                    LazyRow(
                        modifier = Modifier.padding(bottom = 3.dp)
                    ) {
                        items(item.sgPassLines!!) {
                            Column(
                                modifier = Modifier
                                    .padding(end = 6.dp)
                                    .background(
                                        Color(colorHandler(it.strColor)),
                                        shape = RoundedCornerShape(4.dp)
                                    )
                            ) {
                                Text(
                                    it.strName ?: "",
                                    fontSize = 11.sp,
                                    color = Color.White,
                                    fontWeight = FontWeight.W400,
                                    modifier = Modifier.padding(
                                        bottom = 1.dp,
                                        top = 1.dp,
                                        start = 4.dp,
                                        end = 4.dp
                                    )
                                )
                            }
                        }
                    }
                }
            }
            Row(
                modifier = Modifier.padding(start = 10.dp)
            ) {
                EndIconButton("打车")
                EndIconButton(distanceHandler(item.distance))
            }
        }
        // 出口选择处
        if (!item.subSuggestions.isNullOrEmpty() && !item.isOfflineData) {
            SubSuggestionsComp(item.subSuggestions!!)
        }
    }
}

/**
 * 记录卡片项 - 公交站
 */
@Composable
fun BusRecordItem(item: Suggestion) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.Top
    ) {
        Column(modifier = Modifier.weight(1f)) {
            // 主标题
            Row(
                modifier = Modifier.padding(bottom = 7.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(5.dp)
            ) {
                if (!item.isOfflineData) {
                    Img(12.dp)
                }
                Text(
                    item.name ?: "", fontSize = 14.sp, fontWeight = FontWeight.W500,
                )
//                if (item.isBrowsed) {
//                    Text(
//                        "浏览过",
//                        fontSize = 10.sp,
//                        fontWeight = FontWeight.W400,
//                        color = Color(0xff3b74e5),
//                        modifier = Modifier
//                            .background(Color(0xffeef3fe), shape = RoundedCornerShape(6.dp))
//                            .padding(start = 3.dp, end = 3.dp)
//                    )
//                }
            }

            if (!item.sgPassLines.isNullOrEmpty()) {
                var parentWidth = 0
                var showEllipsis by remember { mutableStateOf(false) }
                LazyRow(
                    modifier = Modifier
                        .fillMaxWidth(0.8f)
                        .padding(bottom = 3.dp)
                        .onGloballyPositioned { coordinates ->
                            // 获取当前容器宽度
                            parentWidth = coordinates.size.width
                        }
                ) {
                    items(item.sgPassLines!!) {
                        var exceedPosition by remember { mutableStateOf(false) }
                        if (!exceedPosition) {
                            Column(
                                modifier = Modifier
                                    .padding(end = 6.dp)
                                    .border(
                                        width = 0.3.dp,
                                        color = Color(colorHandler(it.strColor)),
                                        shape = RoundedCornerShape(5.dp)
                                    )
                                    .onGloballyPositioned { coordinates ->
                                        if (coordinates.positionInParent().x + 150 > parentWidth) {
                                            exceedPosition = true
                                            showEllipsis = true
                                        }
                                    }
                            ) {
                                Text(
                                    it.strName ?: "",
                                    fontSize = 11.sp,
                                    color = Color(colorHandler(it.strColor)),
                                    fontWeight = FontWeight.W400,
                                    modifier = Modifier.padding(
                                        bottom = 1.dp,
                                        top = 1.dp,
                                        start = 4.dp,
                                        end = 4.dp
                                    )
                                )
                            }
                        } else {
                            return@items
                        }
                    }
                    if (showEllipsis) {
                        item {
                            Text(
                                "...", fontSize = 10.sp, color = Color(0x88000000),
                                modifier = Modifier.padding(top = 3.dp)
                            )
                        }
                    }

                }
            }
        }
        Row(
            modifier = Modifier.padding(start = 10.dp)
        ) {
            EndIconButton("打车")
            EndIconButton(distanceHandler(item.distance))
        }
    }

}

/**
 * 记录卡片项 - 地点
 */
@Composable
fun PlaceRecordItem(item: Suggestion) {

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.Top
    ) {
        Column(modifier = Modifier.padding(bottom = 3.dp)) {
            BasicRecordTitle(item)
            SecondText(item.address!!)
        }
        Row(
            modifier = Modifier.padding(start = 10.dp)
        ) {
            EndIconButton("打车")
            EndIconButton(distanceHandler(item.distance))
        }
    }
}

/**
 * 记录卡片项 - 坐标搜索
 */
@Composable
fun LatLonRecordItem(item: Suggestion) {

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column {
            BasicRecordTitle(item)
            SecondText(item.address!!, modifier = Modifier.padding(bottom = 3.dp))
            // 经纬度文本
            Row(
                verticalAlignment = Alignment.Bottom
            ) {
                SecondText("纬度:")
                SecondText(item.latLng!!.latitude.toString(), Color(0xff356cd9))
                Spacer(Modifier.width(10.dp))
                SecondText("经度:")
                SecondText(item.latLng!!.longitude.toString(), Color(0xff356cd9))
            }
            SecondText(
                "不支持国外坐标范围，自动调整坐标顺序",
                Color(0x66000000),
                modifier = Modifier.padding(top = 4.dp)
            )
        }
        Row(
            modifier = Modifier.padding(start = 10.dp)
        ) {
            EndIconButton(distanceHandler(item.distance))
        }
    }
}

/**
 * 记录卡片项 - 城市
 */
@Composable
fun CityRecordItem(item: Suggestion) {

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.Top
    ) {
        if (item.isOfflineData) {
            Text(item.name ?: "", fontSize = 14.sp, fontWeight = FontWeight.W500)
        } else {
            Column {
                BasicRecordTitle(item)
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    SecondText("城市地图", color = Color.Black)
                    SecondText("交通快查", color = Color.Black)
                    SecondText("旅行指南", color = Color.Black)
                    SecondText("特色美食", color = Color.Black)
                }
            }
            Row(
                modifier = Modifier.padding(start = 10.dp)
            ) {
                EndIconButton(distanceHandler(item.distance))
            }
        }
    }
}

/**
 * 记录卡片项 - poi
 */
@Composable
fun PoiRecordItem(item: Suggestion) {

    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 卡片主体
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 8.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            if (item.picUrl.isNotBlank() && !item.isOfflineData) {
                Box(
                    modifier = Modifier.size(75.dp)
                        .background(Color.LightGray, shape = RoundedCornerShape(8.dp))
                )
                Spacer(Modifier.width(8.dp))
                Column(
                    modifier = Modifier.weight(1f),
                ) {
                    BasicRecordTitle(item)
                    // 地址
                    Row(
                        modifier = Modifier
                            .width(300.dp).padding(bottom = 4.dp)
                    ) {
                        SecondText(item.address!!, fontSize = 12.sp)
                    }
                    // 评价 人流量 访问相关
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(bottom = 4.dp)
                    ) {
                        Row(
                            modifier = Modifier.padding(end = 8.dp),
                            horizontalArrangement = Arrangement.spacedBy(1.dp)
                        ) {
                            repeat(5) {
                                Img(9.dp)
                            }
                        }
                        if (!item.priceInfo.isNullOrBlank()) {
                            SecondText(
                                item.priceInfo!!,
                                fontSize = 11.sp,
                                modifier = Modifier.padding(end = 2.dp)
                            )
                        } else if (!item.peopleFlow.isNullOrBlank()) {
                            Text(
                                item.peopleFlow!!,
                                fontSize = 10.sp,
                                color = Color(0xff58bf82),
                                fontWeight = FontWeight.W400,
                                modifier = Modifier.padding(end = 2.dp)
                            )
                            Img(10.dp)
                        }
                    }
                    // 类别名
                    Row {
                        Text(
                            item.typeWord!!,
                            fontSize = 12.sp,
                            color = Color(0xff000000),
                            fontWeight = FontWeight.W400,
                            modifier = Modifier.padding(end = 10.dp)
                        )
                        Text(
                            item.poiErrInfo!!,
                            fontSize = 10.sp,
                            color = Color(0xffcf695d),
                            fontWeight = FontWeight.W400,
                        )
                    }
                }
            } else {
                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    BasicRecordTitle(item)
                    Row(
                        modifier = Modifier.padding(bottom = 3.dp)
                            .width(250.dp)
                    ) {
                        if (!item.isOfflineData) {
                            SecondText(item.typeWord!!, modifier = Modifier.padding(end = 8.dp))
                        }
                        SecondText(item.address!!)
                    }
                    // 评价 人流量 访问相关
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // 评分
                        if (item.starLevel != -1) {
                            Row(
                                modifier = Modifier.padding(end = 8.dp),
                                horizontalArrangement = Arrangement.spacedBy(1.dp)
                            ) {
                                repeat(5) {
                                    Img(9.dp)
                                }
                            }
                        }
                        // 人均价格 / 人流量
                        if (!item.priceInfo.isNullOrBlank()) {
                            SecondText(
                                item.priceInfo!!,
                                fontSize = 10.sp,
                                modifier = Modifier.padding(end = 8.dp)
                            )
                        }
                        // 实时人气
                        if (!item.behavior.isNullOrBlank()) {
                            SecondText(
                                item.behavior!!,
                                fontSize = 10.sp,
                                modifier = Modifier.padding(end = 8.dp)
                            )
                        }
                        if (item.priceInfo.isNullOrBlank() && !item.peopleFlow.isNullOrBlank()) {
                            Text(
                                item.peopleFlow!!,
                                fontSize = 10.sp,
                                color = Color(0xff58bf82),
                                fontWeight = FontWeight.W400,
                                modifier = Modifier.padding(end = 2.dp)
                            )
                            Img(10.dp)
                        }
                    }
                }
            }

            Row(
                modifier = Modifier.padding(start = 10.dp)
            ) {
                EndIconButton("打车")
                EndIconButton(distanceHandler(item.distance))
            }
        }

        // 出口选择处
        if (!item.subSuggestions.isNullOrEmpty() && !item.isOfflineData) {
            SubSuggestionsComp(item.subSuggestions!!)
        }

        if (item.miniApp != null && !item.miniApp!!.url.isNullOrBlank()) {
            Row(
                modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 5.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    "[门票预订]",
                    fontSize = 13.sp,
                    fontWeight = FontWeight.W500,
                    color = Color(0xffe66e47),
                    modifier = Modifier.padding(end = 5.dp)
                )
                Text(
                    "线上预约参观",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.W400,
                    color = Color(0xaa000000),
                    modifier = Modifier.padding(end = 5.dp)
                )
                Spacer(Modifier.weight(1f))
                Text(
                    "小程序购票",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.W400,
                    color = Color(0xff4da06b),
                    modifier = Modifier.padding(end = 5.dp)
                )
                Img(12.dp)
            }
        }
    }
}


/**
 * 记录卡片项 - 公交线/地铁线
 */
@Composable
fun LineRecordItem(item: Suggestion) {

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.Top
    ) {
        Column(Modifier.padding(bottom = 3.dp)) {
            BasicRecordTitle(item)
            SecondText(item.showName!!)
        }
    }

}

/**
 * 记录卡片项 - 小程序
 */
@Composable
fun MiniAppRecordItem(item: Suggestion) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(5.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            item.name ?: "", fontSize = 14.sp, fontWeight = FontWeight.W500,
        )
        if (!item.isOfflineData) {
            Text(
                "微信小程序",
                fontSize = 11.sp,
                fontWeight = FontWeight.W400,
                color = Color(0xff50a16d),
                modifier = Modifier
                    .border(0.5.dp, Color(0xff50a16d), shape = RoundedCornerShape(4.dp))
                    .padding(start = 3.dp, end = 3.dp)
            )
            Spacer(Modifier.weight(1f))
            Text(
                item.miniApp?.appButton?.get(0)?.button_name ?: "点击打开",
                fontSize = 12.sp,
                fontWeight = FontWeight.W400,
                color = Color(0xff3d87d8)
            )
            Img(12.dp)
        } else {
            Img(10.dp)
        }
    }
}

/**
 * 记录卡片项 - 底部
 */
@Composable
fun FooterRecordItem(item: Suggestion) {
    Column(
        modifier = Modifier.fillMaxWidth()
            .padding(top = 8.dp)
            .background(
                color = Color.White, shape = RoundedCornerShape(
                    bottomStart = 16.dp,
                    bottomEnd = 16.dp
                )
            )
            .clickable { /* TODO 跳转页面 */ }
            .padding(start = 12.dp, top = 8.dp, end = 12.dp, bottom = 8.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            item.footerText ?: "查看全部结果",
            fontSize = 11.sp,
            fontWeight = FontWeight.W400,
            color = Color(0xdd000000),
        )
    }
}

/* ======== 拆分组件 ==========   */

/**
 * 记录标题
 */
@Composable
fun BasicRecordTitle(item: Suggestion, modifier: Modifier = Modifier) {
    Row(
        modifier = Modifier.padding(end = 5.dp)
            .fillMaxWidth()
    ) {
        var str = ""
        val textList: MutableList<BasicTitle> = mutableListOf()
        var isHighlightText = false
        item.name?.toCharArray()?.forEachIndexed { index, it ->
            if (item.highlightText?.contains(it) == true) {
                if (!isHighlightText) {
                    isHighlightText = true
                    textList.add(BasicTitle(str))
                    str = ""
                }

            } else {
                if (isHighlightText) {
                    isHighlightText = false
                    textList.add(BasicTitle(str, Color(0xff3670eb)))
                    str = ""
                }
            }
            str += it
            if (index == item.name!!.length - 1) {
                textList.add(
                    BasicTitle(
                        str,
                        if (isHighlightText) Color(0xff3670eb) else Color.Black
                    )
                )
            }
        }
        textList.forEach {
            var isOverflow by remember { mutableStateOf(false) }
            if (!isOverflow) {
                Text(
                    it.title, fontSize = 13.sp, fontWeight = FontWeight.W500,
                    color = it.color,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    onTextLayout = { textLayoutResult ->
                        if (textLayoutResult.didOverflowWidth) {
                            isOverflow = true
                        }
                    },
                )
            }
        }
    }
}

data class BasicTitle(
    val title: String,
    val color: Color = Color.Black,
)

/**
 * 副文本
 */
@Composable
fun SecondText(
    str: String,
    color: Color = Color(0x88000000),
    fontSize: TextUnit = 11.sp,
    modifier: Modifier = Modifier
) {
    Text(
        str,
        fontSize = fontSize,
        color = color,
        fontWeight = FontWeight.W400,
        modifier = modifier,
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
    )
}

/**
 * 尾部图标按钮
 */
@Composable
fun EndIconButton(msg: String, modifier: Modifier = Modifier) {

    Column(
        modifier.width(40.dp).padding(top = 5.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Img(16.dp)
        Row(
            modifier = Modifier.padding(top = 4.dp)
        ) {
            Text(
                msg,
                fontSize = 10.sp,
                color = Color(0xff333333),
                fontWeight = FontWeight.W400,
                textAlign = TextAlign.Center
            )
        }
    }
}

/**
 * 子推荐按钮
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun SubSuggestionsComp(subSuggestions: List<Suggestion>, modifier: Modifier = Modifier) {
    FlowRow(
        modifier = Modifier.fillMaxWidth(0.95f).padding(top = 2.dp),
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        subSuggestions.forEach {
            Row(
                modifier = Modifier
                    .width(140.dp)
                    .padding(top = 6.dp)
                    .border(
                        width = 0.5.dp, color = Color(0x11000000),
                        shape = RoundedCornerShape(16.dp)
                    )
                    .background(Color(0xfffcfdff), shape = RoundedCornerShape(16.dp))
                    .padding(
                        top = 8.dp,
                        bottom = 8.dp
                    ),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    it.showName ?: it.name ?: "",
                    fontSize = 11.sp,
                    fontWeight = FontWeight.W400
                )
            }
        }
    }
}

/**
 * 距离处理
 */
fun distanceHandler(dist: String?): String {
    if (dist.isNullOrBlank() || dist == "0") {
        return "路线"
    }
    val distance = dist.toInt()
    if (distance < 1000) {
        return distance.toString() + "米"
    } else {
        var result = ""
        if (distance / 1000 < 100) {
            result = (round((distance / 100).toDouble()) / 10).toString()
            if (result.indexOf(".0") != -1) {
                result = result.substring(0, result.length - 2)
            }
            result += "公里"
        } else if (distance / 1000 < 1000) {
            result = (distance / 1000).toString()
            result += "公里"
        } else {
            result = "去这里"
        }
        return result
    }
}

fun colorHandler(colorStr: String?): Long {
    return if (colorStr.isNullOrBlank()) {
        0xffcccccc
    } else {
        ("ff" + colorStr.substring(1)).toLong(16)
    }
}

/**
 * 分割数字和文本
 */
fun splitStringByNum(str: String): Pair<String, String> {
    var newStr = str
    var lastIndex = -1
    while (newStr.length > 1) {
        if (newStr.last().isDigit()) {
            lastIndex = newStr.length - 1
            break
        } else {
            newStr = newStr.substring(0, newStr.length - 2)
        }
    }

    println("log--> $lastIndex $newStr")
    if (lastIndex > 0 && lastIndex < str.length) {
        return str.substring(0, lastIndex + 1) to str.substring(lastIndex + 1)
    } else {
        return "" to str
    }
}